<template>
  <div id="searchPicturePage">
    <h2 style="margin-bottom: 16px; margin-left: 30px">果酱识图</h2>
    <!-- 原图 -->
    <a-col :sm="24" :md="10">
      <a-card title="原图">
        <a-image
          :al="picture.name"
          :src="picture.url"
          style="max-height: 350px; object-fit: contain"
        />
      </a-card>
    </a-col>
    <h3 style="margin: 16px 0">识图结果</h3>
    <!-- 图片结果列表 -->
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :loading="loading"
    >
      <template #renderItem="{ item: picture }">
        <a-list-item style="padding: 0" v-if="picture.thumbUrl">
          <a :href="picture.thumbUrl" target="_blank">
            <!-- 单张结果图片 -->
            <a-card hoverable style="width: 238px" @click="doClickPictureCard(picture)">
              <template #cover>
                <img :src="picture.thumbUrl" style="height: 180px; object-fit: cover" />
              </template>
            </a-card>
          </a>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue'
import {
  getPictureVoByIdUsingGet,
  searchPictureByPictureUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()

const loading = ref(false)

const picture = ref<API.PictureVO>({})

const pictureId = computed(() => {
  return route.query?.pictureId
})

/**
 * 根据图片Id获取图片详情
 */
const fetchOriginPicture = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({
      // @ts-ignore
      id: pictureId.value,
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error('抱歉，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取图片详情失败，' + e.message)
  }
}

// 识图结果列表
const dataList = ref<API.ImageSearchResult[]>([])
/**
 * 根据图片Id获取识图结果列表
 */
const fetchResultDataList = async () => {
  loading.value = true
  try {
    const res = await searchPictureByPictureUsingPost({
      // @ts-ignore
      pictureId: pictureId.value,
    })
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data ?? []
      message.success('识图成功')
    } else {
      message.error('识图失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('识图失败，' + e.message)
  }
  loading.value = false
}

// 首次进入页面，加载原图和识图结果
onMounted(() => {
  fetchOriginPicture()
  fetchResultDataList()
})
</script>

<style scoped>
#searchPicturePage {
  margin-bottom: 16px;
}
</style>
